
import 'package:dog_read/db/book_db.dart';
import 'package:dog_read/pages/utils/navigator_utils.dart';
import 'package:dog_read/provider/providers.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sqflite/sqlite_api.dart';

class Bookshelf extends StatefulWidget {
  @override
  _BoolshelfState createState() => _BoolshelfState();
}

class _BoolshelfState extends State<Bookshelf> with TickerProviderStateMixin {
  AnimationController animationController;
  Animation animationTop;
  CurvedAnimation curve;

  @override
  void initState() {
    super.initState();
    // 取消先前选中的
    Future.delayed(Duration(milliseconds: 50)).then((value) => 
    Provider.of<BookshelfProvider>(context, listen: false).replaceAll([])
    );
    Provider.of<ShelfProvider>(context, listen: false).initShelfBooks();
    // 动画设置
    animationController = AnimationController(
      duration: Duration(milliseconds: 200),
      vsync: this,
    );

    curve = CurvedAnimation(parent: animationController, curve: Curves.easeInOut);
    animationTop = Tween(begin: 0.0, end: 60.0).animate(curve);
  }


  void _callback(int type) async{
    // 0-取消 1-删除选中 2-全选
    switch (type) {
      case 2:
          List bookIds = [];
          List bookshelfList= Provider.of<ShelfProvider>(context, listen: false).shelfBooks;
          bookshelfList.forEach((element) { 
            bookIds.add(element["book_id"]);
          });
          Provider.of<BookshelfProvider>(context, listen: false).replaceAll(bookIds);
        break;
      case 0:
        Provider.of<BookshelfProvider>(context, listen: false).replaceAll([]);
        break;
      case 1:
        List selectedBooks = Provider.of<BookshelfProvider>(context, listen: false).books;
        Database db = await bookDb;
        for (var bookId in selectedBooks) {
          await db.delete('bookshelf', where: "book_id = ?", whereArgs: [bookId]);
        }
        Provider.of<BookshelfProvider>(context, listen: false).replaceAll([]);
        Provider.of<ShelfProvider>(context, listen: false).initShelfBooks();
        break;
      default:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    Provider.of<ShelfProvider>(context, listen: false).initShelfBooks();
        List bookList = Provider.of<ShelfProvider>(context, listen: true).shelfBooks;
    return Stack(children: <Widget>[
          GridView.builder(
            padding: EdgeInsets.all(8.0),
            itemCount: bookList.length,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3, crossAxisSpacing: 8.0, mainAxisSpacing: 8.0),
            itemBuilder: (BuildContext context, int index) {
              String bookId = bookList[index]["book_id"];
              List selectedBooks = Provider.of<BookshelfProvider>(context, listen: true).books;
              bool isSelected = selectedBooks.contains(bookId);
              return GestureDetector(
                  onLongPress: () {
                    this.animationController.forward();
                  },
                  onTap: () {
                    if (animationController.status == AnimationStatus.completed) {
                      if (!isSelected) {
                        Provider.of<BookshelfProvider>(context, listen: false)
                            .addBook(bookId);
                      } else {
                        Provider.of<BookshelfProvider>(context, listen: false)
                            .removeBook(bookId);
                      }
                    }else{
                      // 导航到对应的书籍详情页面
                      navToBookDetail(context, url: bookList[index]["book_url"], title: bookList[index]["book_title"]);
                    }
                  },
                  child: Container(
                      decoration: BoxDecoration(
                        border: Border.all(
                            color: isSelected ? Colors.lightBlue : Colors.white,
                            width: isSelected ? 3 : 0,
                            style: BorderStyle.solid),
                      ),
                      child: Column(
                        children: <Widget>[
                          Expanded(
                              flex: 10,
                              child: Card(
                                elevation: 0.3,
                                child: Image.network(
                                    bookList[index]["image_url"],
                                    fit: BoxFit.cover),
                              )),
                          Expanded(
                            flex: 2,
                            child: Text("${bookList[index]['book_title']}"),
                          ),
                        ],
                      )));
            },
          ),
          Positioned(
            bottom: 0,
            child: AnimatedTop(
              animations: [animationTop],
              controller: animationController,
              callback: _callback
            ),
          )
        ]);
  }
}

class AnimatedTop extends AnimatedWidget {
  final List animations;
  final AnimationController controller;
  final callback;

  AnimatedTop({this.animations, this.controller, this.callback})
      : super(listenable: controller);

  @override
  Widget build(BuildContext context) {
    return Opacity(
        opacity: 0.9,
        child: Container(
            padding: EdgeInsets.all(0),
            height: animations[0].value,
            width: MediaQuery.of(context).size.width,
            decoration: BoxDecoration(color: Colors.white),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                ActionChip(
                  label: Text("取消"),
                  onPressed: () {
                    this.callback(0);
                    controller.reverse();
                  },
                ),
                ActionChip(
                  label: Text("删除选中"),
                  onPressed: () {
                    this.callback(1);
                    controller.reverse();
                  },
                ),
                ActionChip(
                  label: Text("全选"),
                  onPressed: () {
                    this.callback(2);
                  },
                )
              ],
            )));
  }
}
